package com.tanhua.manage.service;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tanhua.dubbo.server.api.UserLikeApi;
import com.tanhua.manage.enums.LogTypeEnum;
import com.tanhua.manage.enums.SexEnum;
import com.tanhua.manage.mapper.UserInfoMapper;
import com.tanhua.manage.mapper.UserMapper;
import com.tanhua.manage.pojo.Log;
import com.tanhua.manage.pojo.User;
import com.tanhua.manage.pojo.UserInfo;
import com.tanhua.manage.vo.Pager;
import com.tanhua.manage.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
@Slf4j
public class UserService extends ServiceImpl<UserMapper,User> {

    @Autowired
    private RestTemplate restTemplate;



    private static final ObjectMapper MAPPER = new ObjectMapper();


    @Autowired
    private UserFreezeService userFreezeService;

    @Autowired
    private UserMapper userMapper;

    @Reference(version = "1.0.0")
    private UserLikeApi userLikeApi;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private LogsService logsService;


    /**
     *用户数据翻页
     * @param page
     * @param pageSize
     * @param userId
     * @param nickname
     * @param city
     * @return
     */
    public Pager<UserVo> queryByPage(Integer page, Integer pageSize, Long userId, String nickname, String city){

        //调用Mapper进行多表联合查询,得到带有分页数据和UserVo对象的pageData对象
        IPage<UserVo> pageData = this.userMapper.queryByPage(new Page<>(page, pageSize), userId == null ? null : String.valueOf(userId), nickname, city);

        //但此时UserVo对象中的sex属性值为字符串形式的"1"或"2"需要处理性别名称的问题
        pageData.getRecords().forEach(userVo -> {

            //通过枚举类将sex的属性值从"1"或"2"转化成"男"或"女"
            userVo.setSex(SexEnum.getSexByValue(Integer.valueOf(userVo.getSex())));

            //从redis中查询每个用户是否被冻结,如果redis中有记录就说明是冻结状态,如果redis中没有记录说明是正常状态
            userVo.setUserStatus(this.userFreezeService.getFreezeStatusByUserId(userVo.getId())?"2":"1");

        });
        return new Pager<>(pageData);
    }



    /**
     * 用户基本资料
     * @param userId
     * @return
     */
    public UserVo queryUserInfo(Long userId){
        UserVo userVo=new UserVo();
        //根据userId查询user表
        User user = this.getById(userId);
        if(ObjectUtil.isEmpty(user)){
            return userVo;
        }
        //根据userId查询userInfo表
        QueryWrapper<UserInfo> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("user_Id",user.getId());
        UserInfo userInfo = this.userInfoMapper.selectOne(queryWrapper);
        if (ObjectUtil.isEmpty(userInfo)){
            return userVo;
        }

        //从两张表复制属性到UserVo
        BeanUtil.copyProperties(userInfo,userVo);
        BeanUtil.copyProperties(user,userVo);
        //由于userVo的nickname与userInfo的nickName不一致,要重新赋值
        userVo.setNickname(userInfo.getNickName());

        //从redis中查询用户的冻结状态
        userVo.setUserStatus(userFreezeService.getFreezeStatusByUserId(userVo.getId())?"2":"1");

        //从MongoDB中根据用户id查询喜欢数,粉丝数,配对数
        userVo.setCountBeLiked(userLikeApi.queryFanCount(user.getId()));
        userVo.setCountLiked(userLikeApi.queryLikeCount(user.getId()));
        userVo.setCountMatching(userLikeApi.queryMutualLikeCount(user.getId()));


        //查询log表,根据userId查询该用户的最近活跃时间
        QueryWrapper<Log> queryWrapperLog=new QueryWrapper<>();
        queryWrapperLog.eq("user_id",user.getId())
                .orderByDesc("created")
                .last("LIMIT 1");
        Log activeLog = this.logsService.getOne(queryWrapperLog);
        if(null!=activeLog){
            //将最近活跃时间赋值到userVo对象中
            userVo.setLastActiveTime(activeLog.getCreated().getTime());
        }

        //查询log表,根据用户id查询最近登陆地点
        QueryWrapper<Log> queryWrapperLogin=new QueryWrapper<>();
        queryWrapperLogin.eq("user_id",userId)
                .eq("type", LogTypeEnum.LOGIN.getValue())
                .orderByDesc("created")
                .last("LIMIT 1");

        Log loginLog = this.logsService.getOne(queryWrapperLogin);
        if(null!=loginLog){
            userVo.setLastLoginLocation(loginLog.getPlace());
        }

        return userVo;
    }



}